<template v-if="formControl">
	<view :style="formControl.style" class="lib-component__selector">
		<lib-selector-label ref="libSelectorLabelRef" :formControl="formControl" />
		<view class="lib-component__selector-content">
			<view class="selector-box picker-box" :style="formControl.selectorStyle">
				<picker :range="range" :value="rangeIdx" @change="selectChange" mode="selector" class="picker">
					<view v-if="rangeIdx === -1" class="picker-placeholder">{{ formControl.placeholder }}</view>
					<view v-else class="picker-label">{{ selectedLabel }}</view>
				</picker>
			</view>
		</view>
	</view>
</template>

<script>
import libSelectorLabel from '../lib-selector-label/lib-selector-label.vue';
export default {
	name: 'lib-selector-picker',
	components:{
		libSelectorLabel,
	},
	emit: [],
	props: {
		formControl: {
			type: Object,
			default: () => {
				return null;
			},
			required: true,
		}
	},
	data() {
		return {
			value: null,
			/** 选中的label */
			selectedLabel: '',
			/** 选择数据 */
			range: [],
			/** 选中的range索引 */
			rangeIdx: -1,
		}
	},
	methods: {
		init() {
			this.value = this.formControl.value;
			this.formControl.valueChange((value) => {
				this.value = value;
			});

			const options = this.formControl.options || [];
			options.forEach((opt) => {
				this.range.push(`${opt.label}`);
			});
			this.options = options;

			this.setRangeByValue(this.value);
		},
		clear() {
			this.formControl.value = '';
			this.value = '';
		},
		/** 通过 index 设置 range*/
		setRangeByIndex(idx) {
			const options = this.formControl.options || [];
			const option = options[idx];
			if (option) {
				this.rangeIdx = idx;
				this.value = option.value;
				this.selectedLabel = option.label;
			}
		},
		/** 通过 value 设置 range*/
		setRangeByValue(val) {
			const options = this.formControl.options || [];
			const option = options.find(opt => opt.value === val);
			if (option) {
				this.rangeIdx = options.findIndex(opt => opt.value === val);
				this.value = option.value;
				this.selectedLabel = option.label;
			}
		},
		selectChange(e) {
			const idx = e.detail.value;
			this.setRangeByIndex(idx);
		}
	},
	mounted() {
		this.init();
		// console.log(this.formControl);
	},
	watch: {},
}

</script>




<style lang="scss" scoped>
@import "../selector.scss";
</style>